package service

import (
	"chat/utils"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func UploadAvatar(c *gin.Context) {
	file, header, err := c.Request.FormFile("avatar")
	if err != nil {
		utils.RespFail(c.Writer, err.Error())
		return
	}
	defer file.Close()

	// Create the directory if it doesn't exist
	uploadDir := "./static/upload/avatar"
	if err := os.MkdirAll(uploadDir, os.ModePerm); err != nil {
		utils.RespFail(c.Writer, err.Error())
		return
	}

	ext := filepath.Ext(header.Filename)
	filename := strconv.FormatInt(time.Now().UnixNano(), 10) + ext
	filePath := filepath.Join(uploadDir, filename)
	dstFile, err := os.Create(filePath)
	if err != nil {
		utils.RespFail(c.Writer, err.Error())
		return
	}
	defer dstFile.Close()
	_, err = io.Copy(dstFile, file)
	if err != nil {
		utils.RespFail(c.Writer, err.Error())
		return
	}
	url := "http://" + c.Request.Host + "/static/upload/avatar/" + filename
	utils.RespOk(c.Writer, url, "")
}

func UploadFile(c *gin.Context) {
	w := c.Writer
	req := c.Request
	srcFile, head, err := req.FormFile("file")
	if err != nil {
		utils.RespFail(w, err.Error())
		return
	}
	// Generate file name
	suffix := filepath.Ext(head.Filename)
	fileName := fmt.Sprintf("%s%s", strings.TrimSuffix(head.Filename, suffix), suffix)
	// Create folder for today's files if it doesn't exist
	uploadDir := fmt.Sprintf("./static/upload/%s", time.Now().Format("2006-01-02"))
	err = os.MkdirAll(uploadDir, os.ModePerm)
	if err != nil {
		utils.RespFail(w, err.Error())
		return
	}

	dstFilePath := filepath.Join(uploadDir, fileName)
	dstFile, err := os.Create(dstFilePath)
	if err != nil {
		utils.RespFail(w, err.Error())
		return
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		utils.RespFail(w, err.Error())
		return
	}
	url := "http://" + req.Host + "/static/upload/" + time.Now().Format("2006-01-02") + "/" + fileName
	if strings.ToLower(suffix) == ".webm" || strings.ToLower(suffix) == ".mp3" {
		utils.RespOk(w, url, "")
	} else {
		utils.RespOk(w, url, "发送文件成功")
	}
}
func DownloadFile(c *gin.Context) {
	fileDir := c.Query("file")

	type FileResponse struct {
		FileName    string `json:"file_name"`
		FileContent []byte `json:"file_content"`
	}
	// 构建文件路径
	filePath := "static/upload/" + fileDir

	// 打开文件
	file, err := os.Open(filePath)
	if err != nil {
		utils.RespFail(c.Writer, "找不到文件")
		return
	}
	defer file.Close()

	// 读取文件内容
	fileInfo, _ := file.Stat()
	fileSize := fileInfo.Size()
	buffer := make([]byte, fileSize)
	_, err = file.Read(buffer)
	if err != nil {
		utils.RespFail(c.Writer, "读取文件内容失败")
		return
	}
	fileResponse := FileResponse{
		FileName:    fileDir,
		FileContent: buffer,
	}

	utils.RespOk(c.Writer, fileResponse, "下载完成，正在保存")
}

func EmojiList(c *gin.Context) {
	// 获取当前服务器地址
	baseURL := "http://" + c.Request.Host

	// 静态文件夹路径
	staticPath := "./static/emoji"

	// 遍历静态文件夹下的所有文件
	var emojiList []string
	err := filepath.Walk(staticPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			// 拼接当前服务器地址和文件名称
			fileURL := baseURL + "/static/emoji/" + path[len(staticPath)-1:]
			emojiList = append(emojiList, fileURL)
		}

		return nil
	})

	if err != nil {
		// 处理错误
		utils.RespFail(c.Writer, "")
		return
	}

	utils.RespOkList(c.Writer, emojiList, nil)
}
